import random
import redis

from flask import Blueprint, g, jsonify, request
from flask_restful import Api, Resource, reqparse,marshal
from models.models import *
from flask_sqlalchemy import Pagination

from utils.jwt_tool import gen_toen,check_token
from utils.models_fields import *
student_bp = Blueprint("student",__name__)

api = Api(student_bp)


class Login(Resource):
    def get(self ):
        req = reqparse.RequestParser()
        req.add_argument("phone")
        req.add_argument("password")
        args = req.parse_args()
        print("前端的手机号",args['phone'])
        print("前端的密码", args['password'])
        stu_info = Stu.query.filter_by(phone=args['phone']).first()
        print("查询出用户的信息",stu_info)
        stu = marshal(stu_info,stu_fields)
        if stu_info.password == args['password']:
            data = {
                'sid':stu_info.id,
                'sname':stu_info.name
            }
            token = gen_toen(data)
            return jsonify({
                "code":200,
                "msg":"登录成功",
                "token":token,
                "data":stu
            })
        else:
            return jsonify(message='账号或密码错误',code=204)

class SmsCode(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('phone')
        args = parser.parse_args()
        phone = args.get('phone')
        print(phone)
        code = random.randint(1000,9999)
        print(code)
        rds = redis.Redis()
        rds.set(phone,code,ex=300)
        return jsonify(message='发送验证码成功',code=200,data=code)
api.add_resource(SmsCode,'/sms_code')

class CheckSmsCode(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('phone')
        parser.add_argument('smscode')
        args = parser.parse_args()
        smscode = args.get('smscode')
        phone = args.get('phone')
        rds = redis.Redis()
        code = rds.get(phone)
        print(smscode,code.decode())
        if code and code.decode() == smscode:
            user_info = Stu.query.filter_by(phone=phone).first()
            if user_info:
                data = {
                    'sid':user_info.id,
                    'name':user_info.name
                }
                token = gen_toen(data)
                return jsonify(message='登录成功',code=200,token=token)
            else:
                user_info = Stu(phone=phone,password=123)
                db.session.add(user_info)
                db.session.commit()
                data = {
                    'sid':user_info.id,
                    'name':user_info.name
                }
                token = gen_toen(data)
                return jsonify(message='登录成功',code=200,token=token)
        return jsonify(message='验证码过期或错误',code=204)
api.add_resource(CheckSmsCode,'/checksms')

class UpdatePwd(Resource):
    def put(self):
        parser = reqparse.RequestParser()
        parser.add_argument('token')
        parser.add_argument('password')
        args = parser.parse_args()
        token = args.get('token')
        password = args.get('password')
        payload = check_token(token)
        print(payload)
        id = payload['sid']
        stu_info = Stu.query.filter_by(id=id)
        print(stu_info)
        if stu_info:
            stu_info.update({'password':password})
            db.session.commit()
            return jsonify(message='修改密码成功',code=200)
        else:
            return jsonify(message='查询不到此用户',code=204)
api.add_resource(UpdatePwd,'/updatepwd')
class Acce_view(Resource):
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument("id")
        req.add_argument("token")
        args = req.parse_args()
        payload = check_token(args['token'])
        id = payload.get('sid')
        stu = Stu.query.filter(Stu.id == id).first()
        tec = Teacher.query.filter(Teacher.id == args['id']).first()
        if tec in stu.teachers:
            return jsonify({
                "code":400,
                "mgs":"用户已经关注"
            })
        stu.teachers.append(tec)
        db.session.commit()
        return jsonify({
            "code":200,
            "msg":"关注成功"
        })
#修改学生在线状态
class Stusta(Resource):
    def put(self):
        parser = reqparse.RequestParser()
        parser.add_argument('token')
        args = parser.parse_args()
        token = args.get('token')
        payload=check_token(token)
        id = payload['sid']

        print("<<",id)
        stu_info = Stu.query.filter_by(id=id).first()
        print(stu_info.status)
        print(type(stu_info.status))
        if stu_info.status == 0:
            Stu.query.filter_by(id=id).update({'status':1})
            db.session.commit()
            return jsonify(message='在线',code=200,status=stu_info.status)
        else:
            Stu.query.filter_by(id=id).update({'status':0})
            db.session.commit()
            return jsonify(message='离线',code=200,status=stu_info.status)
#所有学生信息
class StuAll(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('page')
        args = parser.parse_args()
        page = args.get('page')
        stu: Pagination = Stu.query.paginate(int(page),2,error_out=False)
        print(stu.items)
        print(stu.total)
        print(stu.page)
        stu_ser = marshal(stu.items,stu_fields)
        data = {
            'stu': stu_ser,
            "page":stu.page,
            "total":stu.total
        }
        rds = redis.Redis()
        rds.publish("teachers",stu.total)
        return jsonify(message='获取成功',code=200,data=data)
#当前登录学生信息
class StuResource(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('token')
        args = parser.parse_args()
        token = args.get('token')
        payload = check_token(token)
        id = payload['sid']
        stu = Stu.query.filter_by(id=id).first()
        if stu:
            stu = marshal(stu,stu_fields)
            return jsonify(message='获取成功',code=200,data=stu)

class UpdateUser(Resource):
    def put(self):
        parser = reqparse.RequestParser()
        parser.add_argument('name')
        parser.add_argument('password')
        parser.add_argument('gender')
        parser.add_argument('img')
        parser.add_argument('token')
        args = parser.parse_args()
        name = args.get('name')
        pwd= args.get('password')
        gender = args.get('gender')
        img = args.get('img')
        token = args.get('token')
        payload = check_token(token)
        id = payload['sid']
        if img:
            # 修改头像
            Stu.query.filter_by(id=id).update({'photo': img})
            db.session.commit()
            return jsonify(message="修改头像成功", code=200)
        if name:
            # 修改昵称
            Stu.query.filter_by(id=id).update({'name': name})
            db.session.commit()
            return jsonify(message="修改成功", code=200)
        if pwd:
            Stu.query.filter_by(id=id).update({'password': pwd})
            db.session.commit()
            return jsonify(message='修改成功', code=200)
        if gender:
            Stu.query.filter_by(id=id).update({'gender': gender})
            db.session.commit()
            return jsonify(message="修改成功", code=200)
api.add_resource(UpdateUser,"/updateuser")

api.add_resource(Login,"/login")
api.add_resource(Acce_view,'/zhong_add')
api.add_resource(Stusta,'/updatestatus')
api.add_resource(StuAll,'/all')
api.add_resource(StuResource,'/detailstu')


class StuCourse(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('token')
        args = parser.parse_args()
        token = args.get('token')
        id = check_token(token)['sid']
        stu = Stu.query.filter_by(id=id).first()
        course = stu.course
        course = marshal(course,course_fields)
        return jsonify(message='获取成功',code=200,data=course)
api.add_resource(StuCourse,'/stucourse')

#轮播图
class CarouseResource(Resource):
    def get(self):
        carouse = Carouse.query.all()
        if carouse:
            print(carouse)

            carouse = marshal(carouse,carouse_fields)
            print(carouse)
            return jsonify(msg='获取成功',code=200,data=carouse)
api.add_resource(CarouseResource,'/carouse')

#学生收藏的老师
class StuTea(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('token')
        args = parser.parse_args()
        token = args.get('token')
        id = check_token(token)['sid']
        stu = Stu.query.filter_by(id=id).first()
        tea = stu.tea
        tea_ser = marshal(tea,teacher_fields)
        return jsonify(msg='获取成功',code=200,data=tea_ser)
api.add_resource(StuTea,'/stutea')

#删除收藏的课程
class CourseDel(Resource):
    def delete(self):
        parser = reqparse.RequestParser()
        parser.add_argument('token')
        parser.add_argument('id')
        args = parser.parse_args()
        token = args.get('token')
        id = args.get('id')
        sid = check_token(token)['sid']
        stu = Stu.query.filter_by(id=sid).first()
        course = Course.query.filter_by(id=id).first()
        stu.course.remove(course)
        db.session.commit()
        return jsonify(msg='删除收藏成功',code=200)



api.add_resource(CourseDel,'/course')
#删除收藏的老师
class TeaDel(Resource):
    def delete(self):
        parser = reqparse.RequestParser()
        parser.add_argument('token')
        parser.add_argument('id')
        args = parser.parse_args()
        token = args.get('token')
        id = args.get('id')
        sid = check_token(token)['sid']
        stu = Stu.query.filter_by(id=sid).first()
        tea = Teacher.query.filter_by(id=id).first()
        stu.tea.remove(tea)
        db.session.commit()
        return jsonify(msg='删除收藏成功',code=200)
api.add_resource(TeaDel,'/tea')
